const express = require('express')
const http = require('http')
const websocket = require('ws')

const app = express()
const server = http.createServer(app)
const wss = new websocket.Server({ server })

wss.on('connection', (ws,req,res) => {
    console.log('Client connected', ws.upgradeReq)
    ws.on('message', (message, req) => {
        console.log(`Received message: ${message}`)
    })
    ws.on('close', () => {
        console.log('Client disconnected')
    })
    ws.on('error', (error) => {
        console.error(`Error: ${error}`)
    })

    ws.send('something', (err) => {
        console.log('err', err)
    });
})

// app.get('/broadcast', (req, res) => {
//     console.log('Broadcasting message to all clients')
//     // console.log('wss', wss.clients)
//     // client.send('Hello from server!')
//     wss.clients.forEach((client) => {
//         console.log('client', client)
//         client.send('Hello from server!')
//     })
//     res.send('Message sent to all clients')
// })

server.listen(3000, () => {
    console.log('Server started on port 3000')
})